<template>
  <div>
    <!-- 面包靴导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 全局区域 -->
    <el-card class="box-card">
      <!-- 添加用户按钮 -->
      <template>
        <el-row>
          <el-col>
            <el-button type="primary" @click="isShow = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </template>

      <!-- 表格区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!--扩展列  -->
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <el-row
              v-for="(item1, i1) in row.children"
              :key="item1.id"
              class="btbuttum vcenter"
              :class="{ bttop: i1 === 0 }"
            >
              <!-- 渲染第一级 -->
              <el-col :span="5">
                <el-tag @close="deleteRight(row, item1.id)" closable>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染第二级和第三季  -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  class="vcenter"
                  :class="{ bttop: i2 !== 0 }"
                >
                  <!-- 第二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRight(row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="deleteRight(row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!--表格主体  -->
        <el-table-column type="index" label="#" width="80px"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="{ row }">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <!-- 编辑角色按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="EditRoles(row.id)"
              >
              </el-button>
            </el-tooltip>

            <!-- 删除角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deleteRoles(row)"
              >
              </el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="设置权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="rolesRights(row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="isShow"
      @close="rolesCloesDialog"
      width="30%"
    >
      <el-form
        ref="rolesRef"
        :model="rolesFrom"
        label-width="80px"
        :rules="rolesRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="isShowEdit"
      @close="rolesEditDialog"
      width="30%"
    >
      <el-form
        ref="rolesRefEdit"
        :model="rolesEdit"
        label-width="80px"
        :rules="rolesRulesEdit"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesEdit.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesEdit.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowEdit = false">取 消</el-button>
        <el-button type="primary" @click="rolesEdittj">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限对话框 -->
    <el-dialog title="权限" :visible.sync="setRightdialogVisible" width="50%">
      <span slot="footer" class="dialog-footer">
        <!-- 树形结构 -->
        <el-tree
          :data="getRolesRigths"
          ref="treeRef"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="dfKeys"
          :props="{ label: 'authName' }"
        ></el-tree>
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 装角色列表的数组对象
      rolesList: [],
      isShow: false,
      isShowEdit: false,
      // 添加角色框验证规则对象
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请键入啊!!!', trigger: 'blur' }
        ]

      },
      // 修改角色验证规则
      rolesRulesEdit: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请键入啊!!!', trigger: 'blur' }
        ]
      },
      // 添加角色数据对象
      rolesFrom: {
        roleName: '',
        roleDesc: ''
      },
      // 保存根据id获取到的数据
      rolesEdit: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      setRightdialogVisible: false,
      getRolesRigths: [],
      dfKeys: [], // 保存第三级id的对象
      roleId: undefined

    }
  },
  created () {
    // 视图创建时调用角色列表
    this.getRolesList()
  },

  methods: {
    async setRight () {
      // 获取数据
      const rids = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      console.log(rids)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,
        {
          rids: rids.join(',')
        })
      this.getRolesRigths = res.data
      this.$message({
        message: '修改权限成功!',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      this.setRightdialogVisible = false
      this.getRolesList()
    },
    // 角色授权管理
    async  rolesRights (role) {
      // this.roleId 哪里的数据?
      this.roleId = role.id
      this.dfKeys = []
      console.log(role)
      const { data: res } = await this.$http.get('rights/tree')
      this.getRolesRigths = res.data
      // 用递归 多传数据
      this.getLeafKeys(role, this.dfKeys)
      this.setRightdialogVisible = true
    },
    // 递归获取所有的id
    getLeafKeys (item, arr) {
      // debugger
      if (!item.children) {
        arr.push(item.id)
      } else {
        item.children.forEach(subItem => {
          this.getLeafKeys(subItem, arr)
        })
      }
    },
    // 根据id删除角色
    deleteRoles (row) {
      const id = row.id
      this.$confirm('您确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await this.$http.delete('roles/' + id)
        this.$message({
          message: '删除成功!',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        this.getRolesList()
      }).catch(() => {

      })
    },
    // 提交修改数据
    rolesEdittj () {
      this.$refs.rolesRefEdit.validate(async isOk => {
        if (!isOk) return false
        const { data: res } = await this.$http.put('roles/' + this.rolesEdit.roleId,
          {
            roleName: this.rolesEdit.roleName,
            roleDesc: this.rolesEdit.roleDesc
          }
        )

        if (res.meta.status !== 200) return this.$message.error('添加失败!')
        this.$message.success('添加成功!')
        this.isShowEdit = false
      })
    },
    // 根据 row.id穿过来的当前行的id进行获取数据操作
    async EditRoles (id) {
      // 打开对话框
      this.isShowEdit = true
      const { data: res } = await this.$http.get('roles/' + id)
      this.rolesEdit.roleId = res.data.roleId
      this.rolesEdit.roleName = res.data.roleName
      this.rolesEdit.roleDesc = res.data.roleDesc
    },
    // 根据id编辑角色列表
    rolesEditDialog () {
      this.$refs.rolesRefEdit.resetFields()
    },
    // 退出对话框清空表单数据
    rolesCloesDialog () {
      this.$refs.rolesRef.resetFields()
    },
    // 添加角色请求
    async addRoles () {
      const { data: res } = await this.$http.post('roles', this.rolesFrom)
      if (res.meta.status !== 200) {
        return this.$message({
          message: res.meta.msg,
          type: 'error',
          showClose: true,
          duration: 3000
        })
      }
      // 添加成功之后 提示添加成功
      this.$message({
        message: '添加成功!',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      this.getRolesList()
      this.isShow = false
    },
    // 删除用户权限
    deleteRight (row, rightId) {
      // 将row.id保存起来
      const roleId = row.id
      // console.log(roleId)

      // 询问是否删除
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        const { data: res } = await this.$http.delete(`roles/${roleId}/rights/${rightId}`)
        // this.getRolesList() //方式1 全部刷新页面
        // console.log(res)
        // 将这一行的数据动态跟新 将res.data动态更新到整个row.children
        row.children = res.data
        this.$message({
          message: '删除成功!',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {

      })
    },
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res.data)
      this.rolesList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bttop {
  border-top: 1px solid #eee;
}

.btbuttum {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  // 垂直居中
  align-items: center;
}
</style>
